package cn.pupil.springframework.util;

import cn.hutool.core.lang.Assert;
import com.sun.istack.internal.Nullable;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description: 数字类型工具
 * @Author: pupil
 * @Date: 2024/12/16 下午 6:31
 */
public class NumberUtils {

    private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);

    private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);

    /**
     * Standard number types (all immutable):
     * Byte, Short, Integer, Long, BigInteger, Float, Double, BigDecimal.
     * 标准数字类型（全部不可变）：
     * 字节、短、整数、长、大整数、浮点数、双精度、大十进制
     */
    public static final Set<Class<?>> STANDARD_NUMBER_TYPES;

    static {
        Set<Class<?>> numberTypes = new HashSet<>(8);
        numberTypes.add(Byte.class);
        numberTypes.add(Short.class);
        numberTypes.add(Integer.class);
        numberTypes.add(Long.class);
        numberTypes.add(BigInteger.class);
        numberTypes.add(Float.class);
        numberTypes.add(Double.class);
        numberTypes.add(BigDecimal.class);
        // 将numberTypes转换为不可修改的Set集合赋值给STANDARD_NUMBER_TYPES
        STANDARD_NUMBER_TYPES = Collections.unmodifiableSet(numberTypes);
    }

    /**
     * Convert the given number into an instance of the given target class.
     * 将给定的数字转换为给定目标类的实例。
     *
     * @param number      the number to convert  要转换的数字
     * @param targetClass the target class to convert to  要转换为的目标类
     * @return the converted number 转换后的数字
     * @throws IllegalArgumentException if the target class is not supported  如果目标类不受支持，@抛出IllegalArgumentException
     *                                  (i.e. not a standard Number subclass as included in the JDK)  即不是JDK中包含的标准Number子类）
     * @see java.lang.Byte
     * @see java.lang.Short
     * @see java.lang.Integer
     * @see java.lang.Long
     * @see java.math.BigInteger
     * @see java.lang.Float
     * @see java.lang.Double
     * @see java.math.BigDecimal
     */
    @SuppressWarnings("unchecked")
    public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass) throws IllegalArgumentException {
        Assert.notNull(number, "Number must not be null");
        Assert.notNull(targetClass, "Target class must not be null");

        // 需要转换的数字是否已经是目标类型或者目标类型的子类
        if (targetClass.isInstance(number)) {
            return (T) number;
        } else if (Byte.class == targetClass) {
            long value = checkedLongValue(number, targetClass);
            if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return (T) Byte.valueOf(number.byteValue());
        } else if (Short.class == targetClass) {
            long value = checkedLongValue(number, targetClass);
            if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return (T) Short.valueOf(number.shortValue());
        } else if (Integer.class == targetClass) {
            long value = checkedLongValue(number, targetClass);
            if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return (T) Integer.valueOf(number.intValue());
        } else if (Long.class == targetClass) {
            long value = checkedLongValue(number, targetClass);
            return (T) Long.valueOf(value);
        } else if (BigInteger.class == targetClass) {
            if (number instanceof BigDecimal) {
                // do not lose precision - use BigDecimal's own conversion
                return (T) ((BigDecimal) number).toBigInteger();
            } else {
                // original value is not a Big* number - use standard long conversion
                return (T) BigInteger.valueOf(number.longValue());
            }
        } else if (Float.class == targetClass) {
            return (T) Float.valueOf(number.floatValue());
        } else if (Double.class == targetClass) {
            return (T) Double.valueOf(number.doubleValue());
        } else if (BigDecimal.class == targetClass) {
            // always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
            // (see BigDecimal javadoc for details)
            return (T) new BigDecimal(number.toString());
        } else {
            throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                    number.getClass().getName() + "] to unsupported target class [" + targetClass.getName() + "]");
        }
    }

    /**
     * Check for a {@code BigInteger}/{@code BigDecimal} long overflow
     * before returning the given number as a long value.
     * 检查是否存在｛@code BigInteger｝/｛@code BigDecimal｝长溢出
     * 然后将给定的数字作为长值返回。
     *
     * @param number      the number to convert 要转换的数字
     * @param targetClass the target class to convert to 要转换为的目标类
     * @return the long value, if convertible without overflow 返回long值，如果可转换而不溢出
     * @throws IllegalArgumentException if there is an overflow 如果发生溢出，则抛出IllegalArgumentException
     * @see #raiseOverflowException
     */
    private static Long checkedLongValue(Number number, Class<? extends Number> targetClass) {
        BigInteger bigInt = null;
        if (number instanceof BigInteger) {
            bigInt = (BigInteger) number;
        } else if (number instanceof BigDecimal) {
            bigInt = ((BigDecimal) number).toBigInteger();
        }

        // 判断是否数据溢出，溢出则抛出IllegalArgumentException错误
        if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) {
            raiseOverflowException(number, targetClass);
        }

        return number.longValue();
    }

    /**
     * Raise an <em>overflow</em> exception for the given number and target class.
     * 为给定的数字和目标类引发<em>溢出</em>异常。
     *
     * @param number      the number we tried to convert 我们试图转换的数字
     * @param targetClass the target class we tried to convert to 我们试图转换为的目标类
     * @throws IllegalArgumentException if there is an overflow 如果发生溢出，则抛出IllegalArgumentException
     */
    private static void raiseOverflowException(Number number, Class<?> targetClass) {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
    }


    /**
     * Parse the given {@code text} into a {@link Number} instance of the given
     * target class, using the corresponding {@code decode} / {@code valueOf} method.
     * <p>Trims all whitespace (leading, trailing, and in between characters) from
     * the input {@code String} before attempting to parse the number.
     * <p>Supports numbers in hex format (with leading "0x", "0X", or "#") as well.
     * 将给定的{@code text}解析为给定的{@link Number}实例
     * 目标类，使用相应的{@code-decode}/{@code-valueOf}方法
     * <p>修剪以下所有空格（前导、尾随和中间字符）
     * 在尝试解析数字之前，请先输入{@code String}。
     * <p>也支持十六进制格式的数字（前导“0x”、“0x”或“#”）。
     *
     * @param text        the text to convert 要转换的文本
     * @param targetClass the target class to parse into 要解析到的目标类
     * @return the parsed number 返回解析后的数字
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     *                                  如果目标类不受支持，@抛出IllegalArgumentException, 即不是JDK中包含的标准Number子类）
     * @see Byte#decode
     * @see Short#decode
     * @see Integer#decode
     * @see Long#decode
     * @see #decodeBigInteger(String)
     * @see Float#valueOf
     * @see Double#valueOf
     * @see java.math.BigDecimal#BigDecimal(String)
     */
    @SuppressWarnings("unchecked")
    public static <T extends Number> T parseNumber(String text, Class<T> targetClass) {
        Assert.notNull(text, "Text must not be null");
        Assert.notNull(targetClass, "Target class must not be null");
        // 调用方法去除字符串的空白字符
        String trimmed = trimAllWhitespace(text);

        if (Byte.class == targetClass) {
            return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed));
        } else if (Short.class == targetClass) {
            return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed));
        } else if (Integer.class == targetClass) {
            return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed));
        } else if (Long.class == targetClass) {
            return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed));
        } else if (BigInteger.class == targetClass) {
            return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed));
        } else if (Double.class == targetClass) {
            return (T) Double.valueOf(trimmed);
        } else if (BigDecimal.class == targetClass || Number.class == targetClass) {
            return (T) new BigDecimal(trimmed);
        } else {
            throw new IllegalArgumentException(
                    "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
        }
    }

    /**
     * Parse the given {@code text} into a {@link Number} instance of the
     * given target class, using the supplied {@link NumberFormat}.
     * <p>Trims the input {@code String} before attempting to parse the number.
     * 将给定的{@code text}解析为
     * 给定的目标类，使用提供的{@link NumberFormat}。
     * <p>在尝试解析数字之前修剪输入{@code String}。
     * @param text the text to convert 要转换的文本
     * @param targetClass the target class to parse into 要转换为的目标类型
     * @param numberFormat the {@code NumberFormat} to use for parsing (if
     * {@code null}, this method falls back to {@link #parseNumber(String, Class)})
     * 格式化用于解析的{@code numberFormat}（如果
     * {@code null}，此方法回退到{@link#parseNumber（String，Class）}）
     * @return the parsed number 回解析后的数字
     * @throws IllegalArgumentException if the target class is not supported
     * (i.e. not a standard Number subclass as included in the JDK)
     * 如果目标类不受支持，@抛出IllegalArgumentException
     * （即不是JDK中包含的标准Number子类）
     * @see java.text.NumberFormat#parse
     * @see #convertNumberToTargetClass
     * @see #parseNumber(String, Class)
     */
    public static <T extends Number> T parseNumber(String text, Class<T> targetClass, @Nullable NumberFormat numberFormat) {
        if (numberFormat != null) {
            Assert.notNull(text, "Text must not be null");
            Assert.notNull(targetClass, "Target class must not be null");
            DecimalFormat decimalFormat = null;
            boolean resetBigDecimal = false;
            // 判断numberFormat是否为DecimalFormat类型
            if (numberFormat instanceof DecimalFormat) {
                decimalFormat = (DecimalFormat) numberFormat;
                // 判断目标类是否为BigDecimal，且decimalFormat解析的不是BigDecimal类型
                if (BigDecimal.class == targetClass && !decimalFormat.isParseBigDecimal()) {
                    // 设置解析字符串时转换为
                    decimalFormat.setParseBigDecimal(true);
                    resetBigDecimal = true;
                }
            }

            try {
                Number number = numberFormat.parse(trimAllWhitespace(text));
                return convertNumberToTargetClass(number, targetClass);
            } catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse number: " + ex.getMessage());
            } finally {
                if (resetBigDecimal) {
                    decimalFormat.setParseBigDecimal(false);
                }
            }
        } else {
            return parseNumber(text, targetClass);
        }
    }

    /**
     * 去除字符串的空白字符
     *
     * @param str
     * @return
     */
    private static String trimAllWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }

        int len = str.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    private static boolean hasLength(@Nullable String str) {
        return (str != null && !str.isEmpty());
    }

    /**
     * Determine whether the given {@code value} String indicates a hex number,
     * i.e. needs to be passed into {@code Integer.decode} instead of
     * {@code Integer.valueOf}, etc.
     * <p>
     * 确定给定的{@code value}字符串是否表示十六进制数，
     * 即需要传递给{@code Integer.decode}，而不是
     * {@code Integer.valueOf}等。
     */
    private static boolean isHexNumber(String value) {
        // 判断是否是负数
        int index = (value.startsWith("-") ? 1 : 0);
        return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index));
    }

    /**
     * Decode a {@link java.math.BigInteger} from the supplied {@link String} value.
     * Supports decimal, hex, and octal notation.
     * 从提供的{@link String}值中解码{@link java.math.BigInteger}。
     * <p>支持十进制、十六进制和八进制表示法。
     *
     * @see BigInteger#BigInteger(String, int)
     */
    private static BigInteger decodeBigInteger(String value) {
        // 进制
        int radix = 10;
        // 数字开始索引
        int index = 0;
        // 负数标记
        boolean negative = false;

        // 判断是否为负数
        if (value.startsWith("-")) {
            negative = true;
            index++;
        }

        // 处理进制说明符号
        if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        } else if (value.startsWith("#", index)) {
            index++;
            radix = 16;
        } else if (value.startsWith("0", index) && value.length() - 1 > 1 + index) {
            index++;
            radix = 8;
        }

        BigInteger result = new BigInteger(value.substring(index), radix);
        return (negative ? result.negate() : result);
    }


}
